
#include <cstdio>
#include <BSocket>
#include "member_BSocket.h"

using namespace BWE;

extern BList<BSocket*>	app_sockets;

#define member					(*(member_BSocket*)_ptr)
#define member_allocate()		_ptr = new member_BSocket(this)
#define member_release()		delete (member_BSocket*)_ptr

BSocket::BSocket()
{
	member_allocate();
	app_sockets.append(this);
}
BSocket::~BSocket()
{
	app_sockets.remove(this);
	if (member.sock)
		close();
	member_release();
}

bool BSocket::flush()
{
	if (member.sock)
	{
#ifdef linux
		return false;
#endif
#ifdef _WIN32
		return false;
#endif
	}
	return true;
}
bool BSocket::close()
{
	if (member.sock)
	{
#ifdef linux
		int ret = ::close(member.sock);
		if (ret == -1)
		{
			puts("close socket");
			return false;
		}
#endif

#ifdef _WIN32
		::closesocket(member.sock);
#endif
		member.sock = 0;
		member.state = State_Closed;
		this->emit(Signal_Disconnected);
		this->emit(Signal_StateChanged, State_Closed);
	}
	return true;
}

bool BSocket::valid() const
{
	return member.sock > 0;
}

const BString& BSocket::address() const
{
	return member.address;
}
int BSocket::port() const
{
	return member.port;
}

BSocket::Error BSocket::error() const
{
	return (Error)member.error;
}
const char* BSocket::errorStr() const
{
	return member.errorStr;
}

BSocket::State BSocket::state() const
{
	return member.state;
}

int BSocket::handle() const
{
	return (int)(member.sock);
}

